<template>
  <div>
    <el-radio
      v-for="item in selectOptions"
      :key="item[valuePropName]"
      v-model="selectedValue"
      :label="item[valuePropName]"
    >
      {{ item[labelPropName] }}
    </el-radio>
  </div>
</template>

<script>
export default {
  name: 'RadioSelector',
  data() {
    return {
      selectedValue: this.value,
      selectOptions: []
    }
  },
  watch: {
    selectedValue() {
      this.$emit('input', this.selectedValue)
    },
    value() {
      this.selectedValue = this.value
    },
    async options() {
      this.selectOptions = await this.getOptions()
    }
  },
  async created() {
    this.selectOptions = await this.getOptions()
  },
  methods: {
    async getOptions() {
      if (Array.isArray(this.options)) {
        return this.options
      }
      if (this.options instanceof Promise) {
        return await this.options
      }
      return this.options.getOptions()
    }
  },
  props: {
    value: {
      type: [String, Number, Object],
      default: null
    },
    options: {
      type: [Array, Object, Function, Promise],
      default() {
        return []
      }
    },
    valuePropName: {
      type: String,
      default: 'value'
    },
    size: {
      type: String,
      default: 'mini'
    },
    labelPropName: {
      type: String,
      default: 'label'
    },
    placeholder: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    }
  }
}
</script>
